import { Component, Input, Output, OnInit, EventEmitter, TemplateRef } from '@angular/core';
import { NziModalService } from "ng-zorro-iop/modal/nzi-modal.service";
import { NzMessageService } from "ng-zorro-antd";
import { Environment } from "environments/environment";
import { FcsService } from "../../service/fcs.service";
import { CommonService } from "../../service/common.service";
import { TriggerCreateComponent } from "../trigger-create/trigger-create.component";
import { Function, Region, Trigger } from "../class/instance";
import { map } from 'rxjs/operators';
import { isObservable } from 'rxjs';
import { ClipboardService } from 'ngx-clipboard';

@Component({
  selector: 'app-trigger-table',
  templateUrl: './trigger-table.component.html',
  styleUrls: ['./trigger-table.component.less']
})
export class TriggerTableComponent implements OnInit {
  @Input() groupList = [];
  @Input() functionList = [];
  groupMap = {}
  functionMap = {}

  @Input() fcsInstance: Function;
  @Input() isDetail = false;
  @Input() groupId = '';
  @Input() functionId = '';
  @Input() type = 'timer';   //触发器类型
  @Input() triggerName = '';
  @Input() groupDisplayName = '';
  @Input() currentRegion: Region;
  @Output() resetTriggerTypes = new EventEmitter<any>();
  @Input() inActions;
  triggerTypeList: Array<any> = Environment.application.triggerTypeList;
  groups = [];
  triggerList = [];
  isLoading = true;
  totalCount = 0;
  pageNo = 1;
  pageSize = 10;
  hasInputValue = false;
  errorMsg = '';
  productUrl: string = Environment.application.productUrl;
  constructor(private commonService: CommonService,
    private fcsService: FcsService,
    private modalService: NziModalService,
    private msgService: NzMessageService,
    private clipboard: ClipboardService) { }

  ngOnInit() {
  }

  ngOnChanges() {
    this.groupList.forEach(item => {
      this.groupMap[item["id"]] = item;
    });
    this.functionList.forEach(item => {
      this.functionMap[item["functionId"]] = item;
    });
  }

  successFun() {
    this.msgService.success('复制成功!');
  }

  trackById(index: number, data: Trigger): string {
    return data.id;
  }

  linkToAPIDetail(data) {//链接到API详情
    if (data.type !== 'apig') {
      return;
    }
    let firstParse = JSON.parse(data['config']);
    let config;
    if (typeof firstParse === 'string') {
      config = JSON.parse(firstParse);
    } else {
      config = firstParse;
    }
    if (!config.id) {
      return;
    }
    let targetUrl = this.productUrl + "/apig/#/openAPI/manage/detail/" + config.id + "?showIndex=0";
    window.open(targetUrl, '_blank');
  }

  createTrigger(fcsInstance?) {
    if (this.fcsInstance) {
      fcsInstance = this.fcsInstance;
    }
    let param = { fcsInstance: fcsInstance, isDetail: this.isDetail, currentRegion: this.currentRegion, triggerType: this.type, functionId: this.functionId, isTriggerList: true };
    if (this.groupId && this.groupId !== '0') {
      param['groupId'] = this.groupId;
    }
    if (!this.isDetail) {
      param['groupId'] = this.groupId;
      param['functionId'] = this.functionId;
      param['triggerType'] = this.type;
    }
    this.modalService.create({
      nzTitle: '创建触发器',
      nzMaskClosable: false,
      nzWidth: '7rem',
      nzContent: TriggerCreateComponent,
      nzComponentParams: param,
      nzOnOk: async createInstance => {
        let isSuccess = await createInstance.submitForm();
        isSuccess && this.getTriggerList(this.groupId, this.functionId);
        this.operateTriggerTypes();
        return isSuccess;
      },
      nzOnCancel: () => {
        this.operateTriggerTypes();
      }
    });
  }

  editTrigger(data) {
    this.modalService.create({
      nzTitle: '配置触发器',
      nzMaskClosable: false,
      nzWidth: '7rem',
      nzContent: TriggerCreateComponent,
      nzComponentParams: { fcsInstance: this.fcsInstance, triggerInstance: data, isDetail: this.isDetail },
      nzOnOk: async createInstance => {
        let isSuccess = await createInstance.submitForm();
        isSuccess && this.getTriggerList(this.groupId, this.functionId);
        this.operateTriggerTypes();
        return isSuccess;
      },
      nzOnCancel: () => {
        this.operateTriggerTypes();
      }
    });
  }

  operateTriggerTypes() {
    if (this.commonService.getObjectArrayIndex(this.triggerTypeList, 'value', 'all') === undefined) {
      this.triggerTypeList.unshift({ "label": "全部触发器", "value": "all" });
    }
    this.resetTriggerTypes.emit({ triggerTypes: this.triggerTypeList });
  }

  deleteTrigger(data) {
    this.modalService.delete({
      nzTitle: '删除触发器',
      nzContentTitle: `确定删除触发器 <em>“${data.name}”</em> 吗？`,
      nzOnOk: () => {
        //返回一个promise对象才可以调用then等函数
        return new Promise((resolve, reject) => {
          this.fcsService.deleteTrigger(data.groupId, data.funcId, data.id).subscribe(
            data => {
              if (data && data.code) {
                resolve(false);
                this.msgService.error(data['message'] || '删除失败！');
              } else {
                resolve(true);
                this.msgService.success('删除成功！');
                if (this.triggerList.length <= 1) {
                  this.pageNo -= 1;
                  this.pageNo = this.pageNo <= 0 ? 1 : this.pageNo;
                }
                this.getTriggerList(this.groupId, this.functionId);
              }
            },
            err => {
              resolve(false);
            }
          );
        });
      },
      nzCancelText: '取消',
      nzOnCancel: () => { },
    });
  }

  accessInvokeUrl(data) {
    //处理data.config
    let firstParse = JSON.parse(data.config);
    let config;
    if (typeof firstParse === 'string') {
      config = JSON.parse(firstParse);
    } else {
      config = firstParse;
    }

    let invokeUrl = "";
    if (data.type == "apig") {
      if (!config['invokeUrl']) {
        this.msgService.error('获取 API 网关触发器 URL 失败')
        return;
      }
      invokeUrl = config['invokeUrl'];
    } else if (data.type == "http") {
      let invokeHost = Environment.application.httpTriggerHost;
      invokeUrl = `${invokeHost}/proxy/${data.accountId}/${data.groupName}/${data.funcName}.${data.targetName}`;
    } else {
      return
    }

    this.modalService.info({
      nzTitle: '提示',
      nzContentTitle: '触发器 URL',
      nzContent: `<a href="${invokeUrl}" target="_blank" rel="noopener noreferrer">${invokeUrl}</a>`,
      nzOkText: "复制 URL",
      nzOnOk: () => {
        this.clipboard.copy(invokeUrl);
        this.msgService.success("复制成功");
      }
    });
  }

  getTriggerList(groupId, functionId) {
    this.isLoading = true;
    this.hasInputValue = this.triggerName == '' ? false : true;
    let triggerType = this.type == "all" ? "" : this.type;
    this.fcsService.getTriggerList(groupId, functionId, this.pageNo, this.pageSize, this.triggerName, triggerType).subscribe(res => {
      this.totalCount = res.totalCount || 0;
      if (res.data) {
        let resData = res.data;
        if (resData.length > 0) {
          if (!this.isDetail) {
            resData.map((item, idx) => {
              item.groupDisplayName = this.groupMap[item.groupId] ? this.groupMap[item.groupId].displayName : "--";
              item.funcName = this.functionMap[item.funcId] ? this.functionMap[item.funcId].functionName : "--";
              return item;
            })
          }
          this.triggerList = resData;
        } else {
          this.triggerList = [];
        }
      }
      if (this.totalCount > 0 && res.data.length <= 0) {
        this.pageNo = Math.floor(this.totalCount / this.pageSize);
        this.pageNo = (this.pageNo === 0 ? 1 : this.pageNo);
        this.getTriggerList(groupId, functionId);
      }
      this.isLoading = false;
    }, error => {
      this.errorMsg = error;
      this.isLoading = false;
    })
  }

  addGroupDisplayNameFromGroups() {
    for (let i = 0; i < this.groups.length; i++) {
      let group = this.groups[i];
      for (let j = 0; j < this.triggerList.length; j++) {
        if (group.id === this.triggerList[j].groupId) {
          this.triggerList[j]['groupDisplayName'] = group.displayName;
        }
      }
    }
  }

}
